import React from 'react';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import { connect } from 'dva';
import config from '../../../../utils/dictionaryConfig';
import { ModalC, ProductGroupTreeC, SecuritiesCodeC, InputNumberC, SelectC, SppIResultC, BusinessTargetC, codeType } from '../../../../comps';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import { isZiGuanEvir } from '../../../../utils/commonFunc';
import style from './index.less';
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 9, offset: 0 },
    md: { span: 9, offset: 0 },
    lg: { span: 9, offset: 0 },
    xl: { span: 8, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 14, offset: 0 },
    xxl: { span: 17, offset: 0 },
  },
};
const FormItemLayout2 = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 4, offset: 0 },
    md: { span: 4, offset: 0 },
    lg: { span: 4, offset: 0 },
    xl: { span: 4, offset: 0 },
    xxl: { span: 3, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 15, offset: 0 },
    sm: { span: 15, offset: 0 },
    md: { span: 15, offset: 0 },
    lg: { span: 16, offset: 0 },
    xl: { span: 19, offset: 0 },
    xxl: { span: 20, offset: 0 },
  },
};
@Form.create()
class addNewC extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sppiSet: false, // 是否可以进行sppi设置
      isZiGuan: false, // 是否资管
      objectives: undefined, //选中的业务目标
      bussniessVisible: false, //业务目标编辑补充是否可见
      addSPPIFlag: false, //点击了新增测试按钮
      SPPI_result: undefined, //根据证券代码获取sppi结果
      objectivesEditObj: {}, //缓存每一个业务目标对应的编辑
      editContent: {}, //业务目标编辑内容
      investmentTypeList: [...investmentTypeData], //投资类型下拉
      SecuritiesCode: undefined, //证券代码相关数据
      price: undefined, // 成本
    };
  }

  componentDidMount() {
    let temp = isZiGuanEvir();
    let isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    this.setState({ isZiGuan });
  }

  // 证券代码改变事件
  tradingCodeChange = (e) => {
    if (e) {
      let findtype = config.holdType.filter((item) => {
        return item.value == e.securityType;
      });
      if (findtype && findtype.length > 0) {
        this.setState({
          listData: findtype,
        });
      } else {
        this.setState({
          listData: [],
        });
      }
      this.state.zqtypeSelect.setSelect(findtype[0]?.value);
      if (findtype[0]?.title == 'ETF' || findtype[0]?.title == '股票' || findtype[0]?.title == '基金') {
        this.setState({ sppiSet: false });
        this.state.investmentTypeSelect.setSelect('FVTPL');
      } else if (
        findtype[0]?.title == '银行间融资回购' ||
        findtype[0]?.title == '银行间融券回购' ||
        findtype[0]?.title == '交易所融资回购' ||
        findtype[0]?.title == '交易所融券回购' ||
        findtype[0]?.title == '协议式正回购' ||
        findtype[0]?.title == '协议式逆回购'
      ) {
        this.setState({ sppiSet: false });
        this.state.investmentTypeSelect.setSelect('AC');
      } else if (findtype[0]?.title == '债券' || findtype[0]?.title == '非标' || findtype[0]?.title == '理财直融') {
        this.setState(
          {
            sppiSet: true,
            SecuritiesCode: e,
          },
          () => {
            this.getSPPI_Result();
          },
        );
      } else {
        this.setState({ sppiSet: false });
        this.state.investmentTypeSelect.setSelect();
      }
    } else {
      this.state.zqtypeSelect.setSelect();
      this.state.investmentTypeSelect.setSelect();
    }
  };

  // 成本改变事件
  changeprice = (e) => {
    const { SecuritiesCode } = this.state;
    if (!this.state.sppiSet) return;
    this.setState(
      {
        price: typeof e == 'number' ? e : undefined, // 把价格放入state方便数量改变时取值使用
      },
      () => {
        if (typeof e == 'string' || SecuritiesCode.securityType != 'zq') return; //当值为123B  这样的数据不请求
        this.getSPPI_Result(); //清空sppi结果 和 校验投资类型值
      },
    );
  };

  //获取sppi结果
  getSPPI_Result = () => {
    const { SecuritiesCode, price } = this.state;
    let query = {};

    if (SecuritiesCode) {
      //证券代码和价格都不为空
      if (SecuritiesCode.securityType == 'zq') {
        if (price == undefined) {
          return;
        }
        query = {
          exchangeCode: SecuritiesCode.exchangeCode,
          tradingCode: SecuritiesCode.tradingCode,
          price: price,
        };
      } else {
        query = {
          exchangeCode: SecuritiesCode.exchangeCode,
          tradingCode: SecuritiesCode.tradingCode,
        };
      }
      this.props.dispatch({
        type: 'bondTradeM/getSPPIResult',
        payload: {
          ...query,
        },
        callback: (data) => {
          let temp;
          if (data) {
            //sppi有值 不可点击新增按钮  无值可以
            temp = data.rgpd;
          } else {
            temp = undefined;
          }
          this.setState(
            {
              SPPI_result: temp,
            },
            () => {
              this.props.form.setFieldsValue({
                SPPI_result: this.state.SPPI_result,
              });
              this.setSelectList();
            },
          );
        },
      });
    } else {
      this.setState(
        {
          SPPI_result: undefined,
        },
        () => {
          this.props.form.setFieldsValue({
            SPPI_result: this.state.SPPI_result,
          });
          this.setSelectList();
        },
      );
      return;
    }
  };

  //设置投资类型下拉 并确定默认值
  setSelectList = () => {
    // 以收取该金融资产合同现金流量为目的	是	AC
    // 以收取该金融资产合同现金流量为目的	否	FVTPL
    // 以收取该合同现金流量及出售金融资产为目的	是	FVOCI
    // 以收取该合同现金流量及出售金融资产为目的	否	FVTPL
    // 其他	是 or 否	FVTPL
    const { SPPI_result, objectives } = this.state;
    if (SPPI_result == undefined || objectives == undefined) {
      this.props.form.setFieldsValue({
        investmentType: undefined,
      });
      this.setState({
        investmentTypeList: investmentTypeData,
      });
      return;
    }
    let arr = [];
    if (objectives == 1 && SPPI_result == 1) {
      //AC
      arr = [{ value: 'AC', title: 'AC' }];
      this.props.form.setFieldsValue({
        investmentType: 'AC',
      });
    } else if ((objectives == 1 && SPPI_result == 2) || (objectives == 2 && SPPI_result == 2) || (objectives == 4 && SPPI_result)) {
      //FVTPL
      arr = [{ value: 'FVTPL', title: 'FVTPL' }];
      this.props.form.setFieldsValue({
        investmentType: 'FVTPL',
      });
    } else if (objectives == 2 && SPPI_result == 1) {
      //FVOCI
      arr = [{ value: 'FVOCI', title: 'FVOCI' }];
      this.props.form.setFieldsValue({
        investmentType: 'FVOCI',
      });
    } else {
      arr = [...investmentTypeData];
      this.props.form.setFieldsValue({
        investmentType: undefined,
      });
    }
    this.setState({
      investmentTypeList: [...arr],
    });
  };

  //业务目标修改
  changeObjectives = (e) => {
    this.setState(
      {
        objectives: e,
      },
      () => {
        this.setSelectList();
      },
    );
  };

  // 模态框内容
  addForm = () => {
    const { sppiSet, isZiGuan, investmentTypeList, editContent, SPPI_result, SecuritiesCode } = this.state;
    const {
      globalM: {
        dataDictionary: { SPPI_USER_DEFINEDTYPE = [], SPPI_BUSSINESS_OBJECTIVES: bussinessObjectivesList = [] },
      },
    } = this.props;

    const tenant = localStorage.getItem('antd-pro-tenant');
    return (
      <div style={{ overflow: 'hidden' }} className={style.info}>
        <Form>
          {/* ***************************第一行************************************* */}
          <Row>
            <Col span={12}>
              <ProductGroupTreeC
                form={this.props.form}
                dataIndex='fundId'
                title='产品组合'
                authority={'write'}
                formItemLayout={FormItemLayout}
                multiple={false}
                positionBody={true}
                rules={[{ required: true, message: `请输入产品组合` }]}
              />
            </Col>
            <Col span={12}>
              <SecuritiesCodeC
                form={this.props.form}
                dataIndex='zqcode'
                codeType={codeType.positioned}
                title='证券代码'
                extraLayout={FormItemLayout}
                rules={[{ required: true, message: `请输入证券代码` }]}
                onChange={(e) => this.tradingCodeChange(e)}
                positionBody={true}
              />
            </Col>
          </Row>
          {/* ***************************第二行************************************* */}
          <Row>
            <Col span={12}>
              <SelectC
                form={this.props.form}
                dataIndex='zqtype'
                title='证券类型'
                formItemLayout={FormItemLayout}
                dataSource={this.state.listData}
                disabled={true}
                rules={[{ required: true, message: `请输入证券类型` }]}
                onRef={(ref) => {
                  this.state.zqtypeSelect = ref;
                }}
              />
            </Col>

            <Col span={12}>
              <InputNumberC
                title='数量'
                dataIndex='amount'
                placeholder='请输入'
                min={1}
                max={999999999999}
                form={this.props.form}
                precision={0}
                formItemLayout={FormItemLayout}
                rules={[
                  { required: true, message: `请输入数量` },
                  { pattern: /^[1-9]/, message: '数量不能小于1' },
                ]}
              />
            </Col>
          </Row>
          {/* ***************************第三行************************************* */}
          <Row>
            <Col span={12}>
              <InputNumberC
                title='成本'
                dataIndex='costPrice'
                placeholder='请输入'
                min={1}
                max={999999999999}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                precision={4}
                onChange={this.changeprice}
                rules={[{ required: true, message: `请输入成本` }]}
              />
            </Col>
            {!sppiSet && (
              <Col span={12}>
                <SelectC
                  form={this.props.form}
                  title='投资类型'
                  dataIndex='investmentType'
                  formItemLayout={FormItemLayout}
                  dataSource={investmentTypeData}
                  rules={[{ required: true, message: '请选择' }]}
                  onRef={(ref) => {
                    this.state.investmentTypeSelect = ref;
                  }}
                />
              </Col>
            )}
          </Row>
          {sppiSet && !isZiGuan ? (
            <Row>
              <Col span={24} className={style.describe_bank}>
                <BusinessTargetC
                  form={this.props.form}
                  rightContentShow={true}
                  dataIndex='bussinessObjectives'
                  disabled={false}
                  onChangeFn={this.changeObjectives}
                  getLayerValue={this.getObjectEdit}
                  formItemLayout={FormItemLayout2}
                  TaretType={1}
                />
              </Col>
            </Row>
          ) : null}
          {sppiSet && !isZiGuan ? (
            <Row>
              <Col span={12}>
                <SppIResultC
                  dataIndex='SPPI_result'
                  title='SPPI结果'
                  formItemLayout={FormItemLayout}
                  form={this.props.form}
                  selectProps={{
                    SecuritiesCode,
                    rightContentShow: sppiSet ? true : false, //右侧按钮是否展示，后面展示后的禁用逻辑，展示逻辑，组件控制
                    SPPI_result: SPPI_result, //根据证券代码切换获取SPPI结果
                    SppItype: 3,
                    sppITitle: '新增测试',
                  }}
                  onOk={this.getSPPI_Result}
                />
              </Col>
              <Col span={12}>
                <SelectC
                  dataIndex='investmentType'
                  form={this.props.form}
                  title='投资类型'
                  disabled={false}
                  formItemLayout={FormItemLayout}
                  dataSource={investmentTypeList}
                  rules={[{ required: true, message: '请选择' }]}
                />
              </Col>
            </Row>
          ) : null}
          {sppiSet && tenant == 'XAYH' && !isZiGuan && (
            <Row>
              <Col span={12}>
                <SelectC
                  dataIndex='userDefinedType'
                  form={this.props.form}
                  title='自定义分类'
                  disabled={false}
                  formItemLayout={FormItemLayout}
                  dataSource={SPPI_USER_DEFINEDTYPE.map((item) => {
                    return { value: item.code, title: item.value };
                  })}
                />
              </Col>
            </Row>
          )}
        </Form>
      </div>
    );
  };

  // 确认
  addanOK = () => {
    const {
      form: { validateFields, resetFields },
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;
      const value = {
        dataDt: moment().format('YYYYMMDD'),
        saveZqCode: fieldsValue.zqcode,
        saveZqlx: fieldsValue.zqtype,
        savecb: fieldsValue.costPrice,
        savesl: fieldsValue.amount,
        savezhbm: fieldsValue.fundId,
        investmentType: fieldsValue.investmentType,
        bussinessObjectives: fieldsValue.bussinessObjectives,
        userDefinedType: fieldsValue.userDefinedType,
        SPPI_result: fieldsValue.SPPI_result,
      };
      this.props.dispatch({
        type: 'positionManageM/addNew',
        payload: value,
        callback: (res) => {
          if (res) {
            resetFields();
            this.props.changeVisible(true);
            this.props.onRefesh(); //刷新列表
          }
        },
      });
    });
  };

  // 取消
  addanCancel = () => {
    const {
      form: { resetFields },
    } = this.props;
    this.props.changeVisible();
    resetFields();
  };

  //存储每一个业绩目标对应的补充编辑
  getObjectEdit = (objectivesEditObj) => {
    this.setState({
      objectivesEditObj,
    });
  };

  render() {
    return (
      <div>
        <ModalC
          title={'新增持仓'}
          visible={this.props.visible}
          maskClosable={false}
          onOk={this.addanOK}
          onCancel={this.addanCancel}
          confirmLoading={this.props.loading.effects['positionManageM/addNew'] === true}
          width={683}
        >
          <div>{this.addForm()}</div>
        </ModalC>
      </div>
    );
  }
}
export default connect(({ positionManage, loading, globalM, bondTradeM }) => ({
  positionManage,
  loading,
  globalM,
  bondTradeM,
}))(addNewC);
